﻿using System.Transactions;

namespace Tszy.Unlimited.Data.UnitOfWorks.Defaults;

/// <summary>
/// 使用 TransactionScope 做为事务的工作单元。
/// </summary>
public class DefaultUnitOfWork : DefaultOfWorkBase
{
    [ThreadStatic] private static TransactionScope _transaction = null;

    /// <summary>
    /// 初始化工作单元。
    /// </summary>
    public DefaultUnitOfWork()
    {
        _transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
    }

    /// <summary>
    /// 提交。
    /// </summary>
    public override void Commit()
    {
        base.Commit();

        _transaction?.Complete();
    }

    /// <summary>
    /// 释放资源。
    /// </summary>
    public override void Dispose()
    {
        if (_transaction != null)
        {
            _transaction?.Dispose();
            GC.SuppressFinalize(this);
        }
        Reset();
    }

    /// <summary>
    /// 重置。
    /// </summary>
    protected override void Reset()
    {
        base.Reset();

        if (_transaction != null)
        {
            _transaction = null;
        }
    }
}